package com.macaline.concurrent;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

class MyTask extends RecursiveTask<Integer>{

    private Integer begin;
    private Integer end;
    private Integer result = 0;

    MyTask(Integer begin, Integer end){
        this.begin = begin;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        if(end - begin < 10){
            System.out.println(Thread.currentThread().getName() + "执行" + begin + "-" + end + "的相加任务。");
            for (int i = begin; i <= end; i++) {
                result += i;
            }
        }else {
            int minddle = (begin + end) / 2;
            MyTask task01 = new MyTask(begin, minddle);
            MyTask task02 = new MyTask((minddle + 1), end);
            task01.fork();
            task02.fork();
            result = task01.join() + task02.join();
        }
        return result;
    }
}

public class ForkJoinDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        MyTask myTask = new MyTask(1, 100);
        ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(myTask);
        System.out.println(forkJoinTask.get());
        forkJoinPool.shutdown();
    }
}
